<script setup lang="ts">
import {Message, Modal} from "@arco-design/web-vue";
import {computed, onMounted, onUnmounted, reactive, ref, watch} from "vue";
import {Form, FormItem, Input, InputPassword} from "@arco-design/web-vue";
import {Button, Checkbox} from "@arco-design/web-vue";
import F_captcha from "@/components/common/f_captcha.vue";
import {getWxLoginOkApi, getWxQrcodeApi, userLoginPwdApi, type userLoginPwdType} from "@/api/user_api";
import {type userLoginCodeType, userLoginCodeApi} from "@/api/user_api";
import {userStorei} from "@/stores/user_store";
import router from "@/router";

const store = userStorei()

async function getSite() {
  await store.getSite()
}

getSite()

interface Props {
  visible: boolean
  isReload?: boolean
  to?: string
}

const props = defineProps<Props>()

const emits = defineEmits(["update:visible"])

function cancel() {
  emits("update:visible", false)
}

function checkType(t: 1 | 2 | 3 | 4 | 5 | 6) {
  form.loginType = t
}

const form = reactive<userLoginPwdType>({
  val: "",
  pwd: "",
  loginType: 3,
  captcha: "",
  captchaID: "",
})

const labelMap = {
  4: "用户名",
  1: "邮箱",
  3: "微信",
  2: "手机号",
  5: "手机号",
  6: "邮箱"
}

const label = computed(() => {
  return labelMap[form.loginType]
})

const captchaRef = ref()
const formRef = ref()

async function pwdLogin() {
  const val = await formRef.value.validate()
  if (val) return
  const res = await userLoginPwdApi(form)
  if (res.code) {
    Message.error(res.msg)
    captchaRef.value.getCaptcha()
    return
  }
  Message.success(res.msg)
  setToken(res.data)

}

const codeForm = reactive<userLoginCodeType>({
  step: 1,
  value: "",
  registerType: 1,
})

const second = ref(60)
const timer = ref<number>(0)

async function sendCode() {
  const val = await formRef.value.validate()
  if (val) return

  codeForm.step = 1

  // 6 email  5 tel
  codeForm.registerType = 1
  if (form.loginType === 5) {
    codeForm.registerType = 2
  }
  const res = await userLoginCodeApi(codeForm)
  if (res.code) {
    Message.error(res.msg)
    captchaRef.value.getCaptcha()
    return
  }
  codeForm.step = 2
  codeBtnDisable.value = true


  timer.value = setInterval(() => {
    second.value--
    if (second.value === 0) {
      codeBtnDisable.value = false
      clearInterval(timer.value)
      second.value = 60
    }
  }, 1000)

  Message.success(res.msg)
}

const codeBtnDisable = ref(false)

async function codeLogin() {
  const val = await formRef.value.validate()
  if (val) return

  // 6 email  5 tel
  codeForm.registerType = 1
  if (form.loginType === 5) {
    codeForm.registerType = 2
  }
  const res = await userLoginCodeApi(codeForm)
  if (res.code) {
    Message.error(res.msg)
    return
  }
  codeForm.step = 1
  Message.success(res.msg)
  setToken(res.data)

}

function setToken(token: string) {
  store.saveUserInfo(token)
  emits("update:visible", false)
  //自动销毁，跳转和重刷
  if (props.to !== "") {
    setTimeout(() => {
      router.push(props.to as string)
    }, 1000)
    return
  }
  if (props.isReload) {
    setTimeout(() => {
      location.reload()
    }, 1000)
  }
}


// 定时器的 id
let qrIntervalId: number | undefined;
let pollIntervalId: number | undefined;
const qruri = ref('');
const ticket = ref('');

// 函数：启动二维码获取与轮询
function startQrPolling() {
  // 初次调用 API 获取二维码
  fetchQrcode();

  // 清除之前的二维码刷新定时器
  clearInterval(qrIntervalId);

  // 设置定时器，每 60 秒重新获取一次二维码
  qrIntervalId = setInterval(async () => {
    await fetchQrcode();
  }, 60000); // 60,000 毫秒 = 60 秒

  // 清除之前的轮询定时器
  clearInterval(pollIntervalId);

  // 每 1 秒轮询 getWxLoginOkApi 接口
  pollIntervalId = setInterval(async () => {
    await pollForToken();
  }, 1000); // 1,000 毫秒 = 1 秒
}

// 监听 loginType 的变化
watch(() => form.loginType, (newValue) => {
  if (newValue === 3) {
    startQrPolling();
  } else {
    // 清除所有定时器，防止不必要的 API 调用
    stopAllPolling();
  }
});

// 函数：清除所有定时器
function stopAllPolling() {
  clearInterval(qrIntervalId);
  clearInterval(pollIntervalId);
}

// 在组件挂载时启动逻辑
onMounted(() => {
  if (form.loginType === 3) {
    startQrPolling();
  }
});

// 在组件销毁时清除定时器
onUnmounted(() => {
  stopAllPolling();
});

// 获取 QR 码地址
async function fetchQrcode() {
  try {
    const response = await getWxQrcodeApi();
    if (response.code === 0 && response.data) {
      console.log(response.data);
      qruri.value = response.data.qruri;
      ticket.value = response.data.ticket;
    } else {
      console.error('Error fetching QR code:', response.msg);
    }
  } catch (error) {
    console.error('Error fetching QR code:', error);
  }
}

// 轮询接口获取 token
async function pollForToken() {
  try {
    if (!ticket.value) return; // 如果没有 ticket，跳过轮询

    const response = await getWxLoginOkApi(ticket.value);
    if (response.code === 0 && response.data) {
      setToken(response.data); // 设置 token
      clearInterval(pollIntervalId); // 成功后停止轮询
    } else if (response.code === 7) {
      // 如果 code 是 7，不做改变
      console.log('Code 7 received, no changes made.');
    } else {
      console.error('Error in polling for token:', response.msg);
    }
  } catch (error) {
    console.error('Error in polling for token:', error);
  }
}


</script>

<template>
  <Modal title="登录" body-class="loginModalBody" :footer="false" hide-title :visible="props.visible" @cancel="cancel">
    <div class="banner">
      木子AI
    </div>
    <div class="body">
      <div class="left">
        <a v-if="store.siteInfo.register.isWxRegister" :class="{active: form.loginType===3}" @click="checkType(3)"
           href="javascript:void (0)">微信登录</a>
        <a v-if="store.siteInfo.login.isEmailLogin" :class="{active: form.loginType===1}" @click="checkType(1)"
           href="javascript:void (0)">邮箱登录</a>
        <a v-if="store.siteInfo.login.isUsernameLogin" :class="{active: form.loginType===4}" @click="checkType(4)"
           href="javascript:void (0)">用户名登录</a>
        <a v-if="store.siteInfo.register.isEmailRegister" :class="{active: form.loginType===6}" @click="checkType(6)"
           href="javascript:void (0)">邮箱注册</a>
        <!--        <a v-if="store.siteInfo.register.isWxRegister" :class="{active: form.loginType===3}" @click="checkType(3)" href="javascript:void (0)">微信登录</a>-->
        <!--        <a v-if="store.siteInfo.login.isEmailLogin" :class="{active: form.loginType===1}" @click="checkType(1)" href="javascript:void (0)">邮箱登录</a>-->
        <!--        <a v-if="store.siteInfo.login.isUsernameLogin" :class="{active: form.loginType===4}" @click="checkType(4)" href="javascript:void (0)">用户名登录</a>-->
        <!--        <a v-if="store.siteInfo.register.isEmailRegister" :class="{active: form.loginType===6}" @click="checkType(6)" href="javascript:void (0)">邮箱注册</a>-->
      </div>
      <div class="right">
        <Form ref="formRef"
              :model="(form.loginType === 4 || form.loginType === 1 || form.loginType === 2) ? form : codeForm"
              :label-col-props="{span:0}" :wrapper-col-props="{span: 24}">
          <div v-if="form.loginType === 4 || form.loginType === 1 || form.loginType === 2">
            <FormItem :label="label" validate-trigger="blur" field="val"
                      :rules="{required: true, message: `请输入${label}`}">
              <Input v-model="form.val" :placeholder="label"></Input>
            </FormItem>
            <FormItem label="密码" validate-trigger="blur" field="pwd" :rules="{required: true, message:'请输入密码'}">
              <InputPassword v-model="form.pwd" placeholder="密码"></InputPassword>
            </FormItem>
            <FormItem label="图形验证码" class="captcha_item" field="captcha" validate-trigger="blur"
                      :rules="{required: true, message:'请输入图形验证码'}">
              <Input v-model="form.captcha" placeholder="图形验证码"></Input>
              <F_captcha ref="captchaRef" default-show v-model="form.captchaID"></F_captcha>
            </FormItem>
            <Button @click="pwdLogin" long type="primary">登录</Button>
          </div>
          <div v-if="form.loginType === 5 || form.loginType === 6">
            <FormItem :label="label" validate-trigger="blur" field="value"
                      :rules="{required: true, message: `请输入${label}`}">
              <Input v-model="codeForm.value" :placeholder="label"></Input>
            </FormItem>
            <FormItem label="图形验证码" class="captcha_item" field="captcha" validate-trigger="blur"
                      :rules="{required: true, message:'请输入图形验证码'}">
              <Input v-model="codeForm.captcha" placeholder="图形验证码"></Input>
              <F_captcha ref="captchaRef" default-show v-model="codeForm.captchaId"></F_captcha>
            </FormItem>
            <FormItem label="验证码" class="captcha_item" field="code" validate-trigger="blur"
                      :rules="{required: codeForm.step === 2, message:'请输入验证码'}">
              <Input :disabled="codeForm.step === 1" v-model="codeForm.code" placeholder="验证码"></Input>
              <Button @click="sendCode" style="margin-left: 10px" type="primary" :disabled="codeBtnDisable">
                发送验证码 {{ codeBtnDisable ? second : '' }}
              </Button>
            </FormItem>
            <Button @click="codeLogin" :disabled="codeForm.step === 1" long type="primary">登录</Button>
          </div>
          <div v-if="form.loginType === 3">
            <div class="qrcode">
              <div v-if="!qruri" class="loading-spinner">加载中...</div>
              <img v-else :src="qruri" alt="QR Code" class="qrcode-image">
            </div>
          </div>
          <div class="user_agreement">
            注册成功表示同意 <a href="">用户协议</a>
          </div>

        </Form>

      </div>
    </div>
  </Modal>
</template>

<style lang="less">
.loginModalBody {
  padding: 0 !important;
  height: 400px;
  border-radius: 5px;
  overflow: hidden !important;

  .banner {
    height: 130px;
    background-image: url("@/assets/img/AI_system_logo_cat_style_blue_white.png");
    background-size: cover;
    background-position-y: -10px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 35px;
    font-weight: 600;
  }

  .body {
    display: flex;
    padding: 20px;

    .left {

      width: 150px;
      display: flex;
      flex-direction: column;
      align-items: center;

      a {
        height: 45px;
        display: flex;
        align-items: center;
        color: var(--color-text-2);
      }

      a.active {
        color: #165dff;
      }
    }

    .right {
      width: calc(100% - 150px);
      display: flex;
      align-items: center;
      justify-content: center;
      border-left: @f_border;
      padding: 0 20px;

      .captcha_item {
        display: flex;

        img {
          height: 32px;
          margin-left: 10px;
          border-radius: 5px;
        }
      }

      .qrcode {
        text-align: center;
        display: flex; /* 添加 flex 布局 */
        align-items: center; /* 垂直居中 */
        justify-content: center; /* 水平居中 */
        height: 140px; /* 确保容器的高度 */

        .loading-spinner {
          font-size: 16px;
          color: #666;
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%; /* 使 loading 占据整个容器 */
        }

        .qrcode-image {
          display: block; /* 确保图片是块级元素 */
          width: 140px;
          height: 140px;
          object-fit: contain; /* 确保图片适应容器大小，保持比例 */
        }
      }


      .user_agreement {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 5px;

        .arco-checkbox {
          margin-right: 5px;
        }
      }
    }
  }
}
</style>